package com.liaoyifan.core.filter;

import com.liaoyifan.core.constant.Constants;
import com.liaoyifan.core.constant.Properties;
import com.liaoyifan.core.exception.NotFoundException;
import com.liaoyifan.core.util.SpringContext;
import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import lombok.extern.log4j.Log4j2;
import org.springframework.core.env.Environment;
import org.springframework.web.servlet.HandlerExceptionResolver;

@SuppressWarnings("unused")
@Log4j2
public class OpenApiFilter implements Filter {

    private final HandlerExceptionResolver handlerExceptionResolver;

    public OpenApiFilter(HandlerExceptionResolver handlerExceptionResolver) {
        this.handlerExceptionResolver = handlerExceptionResolver;
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        Environment environment = SpringContext.getEnvironment();
        boolean isRelease =
                Constants.RELEASE.equals(SpringContext.getEnvironment().getActiveProfiles()[0]);
        boolean openApiEnable =
                environment.getProperty(Properties.OPEN_API_ENABLE, Boolean.class, false);
        if (isRelease || !openApiEnable) {
            this.handlerExceptionResolver.resolveException(
                    (HttpServletRequest) request,
                    (HttpServletResponse) response,
                    null,
                    new NotFoundException());
            return;
        }
        chain.doFilter(request, response);
    }
}
